<template>
  <div class="view-fill">
    <div class="app-container-flex">
      <NewFullScreen
        v-model="showDialog"
        :title="title || '维修委外申请修改'"
        :needReturn="!flowFormType"
      >
        <template v-slot:full-button>
          <el-button
            v-if="
              !id &&
              $permission('outsourcingApplication:saveAndSubmit') &&
              !flowFormType
            "
            @click="saveAndSubmit()"
            >保存并提交</el-button
          >
          <el-button v-if="!flowFormType" @click="save()">保存</el-button>
        </template>
        <div class="model-panel">
          <div class="model-panel-title">
            <p>{{ $t('basic_information') }}</p>
          </div>
          <div class="model-panel-body">
            <page-form
              class="paddingBox order-model-formBox flex_wrap_start_start"
              v-model:ref-obj="formInfo.ref"
              :data="formInfo.data"
              :field-list="formInfo.fieldList"
              :label-width="formInfo.labelWidth"
              :rules="formInfo.rules"
            >
              <template v-slot:form-repairOrderNo>
                <el-input
                  v-model="formInfo.data.repairOrderNo"
                  :class="props.id ? '' : 'not-mongolia'"
                  type="input"
                  :required="true"
                  :disabled="true"
                  placeholder="请选择报修单据号"
                >
                  <template #append>
                    <el-icon @click="_selectRepairOrder"
                      ><MoreFilled
                    /></el-icon>
                  </template>
                </el-input>
              </template>
              <template v-slot:form-entrustOrgName>
                <el-input
                  v-model="formInfo.data.entrustOrgName"
                  class="not-mongolia"
                  type="input"
                  :required="true"
                  :disabled="false"
                  placeholder="请选择委托维修机构"
                >
                  <template #append>
                    <el-icon @click="selectExecCoordinationUser"
                      ><MoreFilled
                    /></el-icon>
                  </template>
                </el-input>
              </template>
              <template v-slot:form-contactUser>
                <el-input
                  v-model="formInfo.data.contactUser"
                  class="not-mongolia"
                  type="input"
                  :required="true"
                  :disabled="true"
                  placeholder="请选择委托联系人"
                >
                  <template #append>
                    <el-icon @click="selectContactUser"><MoreFilled /></el-icon>
                  </template>
                </el-input>
              </template>
              <template v-slot:form-estimatedCost>
                <div class="flex">
                  <el-input-number
                    v-model="formInfo.data.estimatedCost"
                    controls-position="right"
                    :min="0"
                    :max="999999999999999999"
                    :precision="
                      $store.state.permission.systemConfig
                        .assets_price_precision
                    "
                    placeholder="请输入预估费用"
                    class="flex-input"
                  >
                  </el-input-number>
                </div>
              </template>
            </page-form>
          </div>
        </div>
      </NewFullScreen>
      <select-repair-order
        v-if="selectRepairOrderInfo.visible"
        v-model:show-dialog="selectRepairOrderInfo.visible"
        :exclude-query-list="selectRepairOrderInfo.excludeQueryList"
        :query="selectRepairOrderInfo.query"
        :queryParams="selectRepairOrderInfo.queryParams"
        :searchList="selectRepairOrderInfo.searchList"
        tableKey="entrustMaintenanceApplySelectRepairList-com.slip.spd.entity.vo.repair.RepairOrderVO"
        :check-box="false"
        :highlight-row="true"
        @callback="selectRepairOrderCallBack"
      />
      <SelectUsers
        v-if="contactUserInfo.visible"
        v-model:show-dialog="contactUserInfo.visible"
        :query="contactUserInfo.query"
        :api="contactUserInfo.api"
        :check-box="false"
        :highlight-row="true"
        @callback="selectContactUserInfoBack"
      />
      <select-org
        v-if="orgInfo.visible"
        v-model:show-dialog="orgInfo.visible"
        v-model:query="orgInfo.query"
        :api="getMaintenancePage"
        :fieldList="orgInfo.fieldList"
        :check-box="false"
        :highlight-row="true"
        :title="请选择委托维修机构"
        @callback="callBackSupplier"
        @reset="reset"
      />
    </div>
  </div>
</template>

<script setup nmae="BrandModify">
import { getRrgUserList } from '@/api/base'
import { getMaintenancePage } from '@/api/core'
import {
  createOutsourcingApplication,
  createOutsourcingApplicationAndSave,
  submitOutsourcingApplication,
  updateOutsourcingApplication,
  detailOutsourcingApplication,
} from '@/api/repair'
const { proxy } = getCurrentInstance()
const emit = defineEmits()

const props = defineProps([
  'visible',
  'id',
  'title',
  'flowFormType',
  'exportId',
])
const orgInfo = ref({
  visible: false,
  query: {
    searchType: 'org',
    searchField: 'maintenanceId',
    sort: 'create_time desc,id asc',
    supplierAuth: '',
  },
  fieldList: [
    { label: '名称', value: 'maintenanceName' },
    { label: '编码', value: 'maintenanceCode' },
  ],
})
const formRefs = ref([])
const formInfo = reactive({
  ref: null,
  data: {},
  fieldList: [
    {
      label: '报修单据号',
      value: 'repairOrderNo',
      type: 'slot',
    },
    {
      label: '委外申请单号',
      value: 'orderNo',
      type: 'input',
      disabled: true,
    },
    {
      label: '报修类型',
      value: 'repairTypeName',
      type: 'select-model',
      code: 'repair_type_enum',
      required: true,
      disabled: true,
    },
    {
      label: '资产卡片号',
      value: 'assetCode',
      type: 'input',
      disabled: true,
    },
    {
      label: '资产名称',
      value: 'assetName',
      type: 'input',
      disabled: true,
    },
    {
      label: '资产位置',
      value: 'location',
      type: 'input',
      disabled: true,
    },
    {
      label: '使用部门',
      value: 'useDeptName',
      type: 'input',
      disabled: true,
      show: true,
    },
    {
      label: '故障时间',
      value: 'faultTime',
      type: 'input',
      disabled: true,
      show: true,
    },
    {
      label: '故障部位',
      value: 'faultPart',
      type: 'input',
      disabled: true,
      show: true,
    },
    {
      label: '故障描述',
      value: 'faultDescribe',
      type: 'input',
      disabled: true,
      show: true,
    },
    {
      label: '要求完成时间',
      value: 'requireCompleteTime',
      type: 'input',
      disabled: true,
      show: true,
    },
    {
      label: '预估费用',
      value: 'estimatedCost',
      type: 'slot',
    },
    {
      label: '委托维修机构',
      value: 'entrustOrgName',
      type: 'slot',
    },
    {
      label: '委托联系人',
      value: 'contactUser',
      type: 'input',
    },
    {
      label: '委托联系电话',
      value: 'contactPhone',
      type: 'input',
      show: true,
    },
    {
      label: '备注',
      value: 'remark',
      type: 'textarea',
    },
  ],
  rules: {
    repairOrderNo: [
      { required: true, message: '请选择报修单据号', trigger: 'change' },
    ],
    entrustOrgName: [
      { required: true, message: '请选择委托维修机构', trigger: 'change' },
    ],
    estimatedCost: [
      { required: true, message: '请输入预估费用', trigger: 'blur' },
    ],
    contactPhone: [
      {
        required: false,
        validator: proxy.$validate.cellphone,
        message: '请输入正确的联系电话',
        trigger: 'blur',
      },
    ],
  },
  labelWidth: '120px',
})
const fullInfo = reactive({
  btnList: [{ label: '保存', event: save, show: true }],
})
const selectRepairOrderInfo = reactive({
  visible: false,
  excludeQueryList: [],
  searchList: [
    {
      label: '使用状态',
      value: 'status',
      type: 'select-model',
      code: 'repair_order_status',
      onlyShowOption: ['1', '2', '3', '5'],
    },
  ],
  query: {
    status: {
      queryType: 'IN',
      value: '1,2,3,5',
    },
  },
  queryParams: {
    isEntrustMaintenanceApplyQuery: 0,
  },
})
const contactUserInfo = reactive({
  visible: false,
  api: getRrgUserList,
  type: '',
  query: {
    hasAllDept: 1,
  },
  row: {},
})
const showDialog = computed({
  get() {
    return props.visible
  },
  set(newValue) {
    emit('update:visible', newValue) // 更新父组件visible
  },
})

onMounted(() => {
  if (props.id) {
    getDetails()
  }
})
function callBackSupplier(row) {
  if (row) {
    formInfo.data.entrustOrgId = row.id
    formInfo.data.entrustOrgName = row.maintenanceName || ''
  }
}
function reset() {
  orgInfo.value.visible = false
}
// flowData 外部流程页面调用
function saveAndSubmit(flowData) {
  save(true, flowData)
}
function save(isSaveAndSubmit, obj = {}) {
  formRefs.value = [formInfo.ref]
  proxy.$fn.checkForm(formRefs.value).then(() => {
    const data = formInfo.data
    let api = data.id
      ? updateOutsourcingApplication
      : isSaveAndSubmit === true
      ? createOutsourcingApplicationAndSave
      : createOutsourcingApplication
    let flowParams = data
    if (isSaveAndSubmit) {
      if (proxy.$route.query.processInstanceId) {
        api = submitOutsourcingApplication
      }
      delete data.completeTime
      flowParams = {
        orderData: data,
        // flowTaskCommentDto和processDefinitionKey为审批流程需要传递的参数
        flowTaskCommentDto: { approvalType: 'submit' },
        processDefinitionKey: 'outsourcingApplication',
        processInstanceId: obj.processInstanceId,
        taskId: obj.taskId,
      }
    }
    if (!data.id) {
      delete data.completeTime
    }
    api(flowParams).then((resp) => {
      if (resp && resp.success) {
        showDialog.value = false
        emit('returnBack')
        emit('returnModify')
      }
    })
  })
}
function _selectRepairOrder() {
  if (props.id) {
    return
  }
  selectRepairOrderInfo.visible = true
}
function selectRepairOrderCallBack(data = undefined) {
  if (data && data.id) {
    formInfo.data = { ...formInfo.data, ...data }
    formInfo.data.repairId = data.id
    formInfo.data.repairOrderNo = data.orderNo
    formInfo.data.remark = ''
    delete formInfo.data.id
    delete formInfo.data.orderNo
  }
}
function selectContactUser() {
  contactUserInfo.visible = true
}
function selectContactUserInfoBack(data) {
  if (data && data.id) {
    formInfo.data['contactUser'] = data.name
  } else {
    formInfo.data['contactUser'] = ''
  }
}
function selectExecCoordinationUser() {
  let ids = []
  /*  res.data.map((item) => {
    ids.push(item.maintenanceId)
  }) */
  orgInfo.value.query.idNotIn = ids.toString()
  orgInfo.value.visible = true
}
function getDetails() {
  detailOutsourcingApplication(props.id).then((resp) => {
    if (resp && resp.success) {
      formInfo.data = resp.data
    }
  })
}
// 名称不要做改变，在流程引擎中需要通过refs进行调用
defineExpose({
  save,
  saveAndSubmit,
})
</script>

<style scoped lang="scss">
.flex {
  width: 100%;
  display: flex;
  flex: 1;
}
.flex-select :deep(.el-input--small .el-input__inner) {
  height: 28px !important;
}
:deep(.el-input-number) {
  width: 100%;
}
:deep(.patrolPlan-checkbox) {
  padding: 0 5px 5px 5px;
  box-sizing: border-box;
  .el-checkbox-button__inner {
    width: 30px;
    height: 30px;
    padding: 0;
    display: flex;
    align-items: center;
    justify-content: center;
  }
}
:deep(.el-checkbox-button__inner) {
  border: 1px solid #dcdfe6 !important;
}
</style>
